<?php
//prt($_SERVER);
require_once 'core/Debug.php'; //System Debug...
require_once 'core/config.php';//System Config...
require_once 'core/Init.php';  //System Init...
require_once 'core/FaceLib.php';  //Cac ham facebook
require_once 'core/PostLib.php';  //Cac ham post belive

require_once 'includes/facebook.php';
$input = array();

//GET DATA
$input['logined']   = FunctionLib::getParamInt('logined', 0);
$input['id']   		= FunctionLib::getParamInt('id', 0);
$input['do']        = FunctionLib::getParam('do', '');
$input['content']  	= FunctionLib::getParam('iptPost', '');
$input['type']  	= isset($_POST['chkOwner']) ? 1 : 0;
//prt($input);

$param = '';
if($input['do'] == 'belive') {
	$param = '?do=belive';
	if($input['pid'] > 0) {
		$param .= '&id='.$input['id'];
	}
}
if($input['id'] == 0){
	//redirect after login
	header("Location: ".FB_BASE_URL);
}
elseif($input['logined']){
	//redirect after login
	header("Location: ".FB_BASE_URL.$param);
}

//Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
    'appId'     => FB_API_KEY,
    'secret'    => FB_SECRET,
    'cookie'    => true
));



//Get User ID
$user = $facebook->getUser();
if($user) {
	try {
		// Proceed knowing you have a logged in user who's authenticated.
		$fbme = $facebook->api('/me'); //prt($fbme);
		$fbprofile = $facebook->api('/'.$input['id']); //prt($fbprofile);

        if($input['do'] == 'share') {
			$data = array (
				'message'       => 'tin rằng:',
				'description'	=> PostLib::getContentBelive(array('owner' => $input['type'], 'fbid' => $fbprofile['id'], 'fbname' => $fbprofile['name'], 'content' => $input['content'])),
				'text'			=> ($input['type']) ? 'Tin '.$fbprofile['name'] : 'Tin điều này',
				'title'			=> ($input['type']) ? $fbprofile['name'] : '',
				'src'			=> ($input['type']) ? FaceLib::getProfileImageUrl($fbprofile['id']) : '',
				'link_image'	=> '',
				'caption'		=> ''
			);
			//update DB
			$valInsert = array(
				'fbid' => $fbprofile['id'],
				'fbname' => $fbprofile['name'],
				'fblink' => $fbprofile['link'],
				'owner' => $input['type'],
				'content' => $input['content'],
				'created' => TIME_NOW,
				'ids_belive' => $fbprofile['id']
			);
			//prt($data);
			$insert_id = DB::insert(T_POST_BELIVE, $valInsert);
			$data['link'] = FB_BASE_URL.'?do=belive&pid='.$insert_id;
			$data['link_image'] = 'http://facebook.com/profile.php?id='. $fbprofile['id'];
            
            //post to Facebook
            FaceLib::postContentToWall($data);
        }
		
		require_once ROOT_PATH.'core/Pagging.php';
		$item_per_page = 30;
		$profilePost = array();
		$arrPostID = array();
		$sql = "SELECT post_id FROM " . T_BELIVE . " WHERE fbid = ".$fbprofile['id']." ORDER BY created DESC";
		$re = Pagging::pager_query($sql,$item_per_page);
		if($re) {
			while ($row=mysql_fetch_assoc($re)){
				$arrPostID[] = $row['post_id'];
			}
			$strPostID = implode(',', $arrPostID);
			$sql = "SELECT * FROM " . T_POST_BELIVE . " WHERE id IN($strPostID) ORDER BY created DESC";
			$profilePost = DB::fetch_all($sql);
		}
		

	} catch (FacebookApiException $e) {
		error_log($e);
		$user = null;
	}
}
else {
	$loginUrl = $facebook->getLoginUrl(array(
		'redirect_uri' => 'http://baodp.todo.vn/ibelive/?logined=1',
		'scope' => 'publish_stream,offline_access'
	));
	
	//header("Location: $loginUrl");
}

// VAR for HTML
$i = 0;

/***********************************
*	HTML
************************************/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/">
<head>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<meta property="fb:admins" content="1311054854" />

	<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
	<script type="text/javascript">
		<? if(!$user) {?>
			top.location.href = "<?=$loginUrl?>";
		<? }//if ?>
	
        function framesetsize(w,h){
            var obj =   new Object;
            obj.width=w;
            obj.height=document.body.scrollHeight;
            FB.Canvas.setSize(obj);
        }
		
		var BASE_URL = "http://baodp.todo.vn/ibelive/";
    </script>
    <script type="text/javascript" src="javascript/jquery/jquery.js"></script>
    <script type="text/javascript" src="javascript/core.js"></script>
    <script type="text/javascript" src="javascript/run.js"></script>
    
    <link rel="stylesheet" href="design/css/default.css" type="text/css" />
	<link rel="stylesheet" href="design/css/style.css" type="text/css">
	<link rel="shortcut icon" type="image/ico" href="design/images/G.ico" />

	<title>Bạn đang tin điều gì ?</title>
</head>
<body onload="framesetsize(500,2500)">
<div id="fb-root"></div>
<? if($user) { ?>
<form id="frmShareBelive" name="frmShareBelive" method="POST">
<input type="hidden" id="do" name="do" value="share" />
<div class="fl pLeft10 pTop15" style="width:180px">
	<div><?=FaceLib::getProfileImage($fbprofile, 'large')?></div>
	<div class="mTop10">
		<ul class="emSideBar">
			<li><a href="#" class="item"><span class="imgWrap"><i class="icon wall"></i></span>Tường</a></li>
			<li><a href="#" class="item"><span class="imgWrap"><i class="icon info"></i></span>Thông tin</a></li>
		</ul>
	</div>
	<? if(isset($fbprofile['bio'])) { ?>		
	<div class="mTop10">
		<div class="emHeaderBox pLeft5">Giới thiệu</div>
		<ul class="mTop10 pLR5">
			<li><?=$fbprofile['bio']?></li>
		</ul>
	</div>
	<? } ?>
	<div class="mTop10">
		<ul class="emBeliveBox mTop10 pLR5" style="border-top:1px solid #EEEEEE;">
			<li>Tin tưởng: <br/><span class="b" style="font-size:18px">50.000</span> điều</li>
			<li>Được bạn bè tin: <br/><span class="b" style="font-size:18px">100.000</span> điều</li>
		</ul>
	</div>
</div>
<div class="fl w520 pLeft20" style="border-left:1px solid #B3B3B3;padding-bottom:40px">
	<div class="mTop20">
		<div style="font-size:20px;font-weight:bold"><?=$fbprofile['name']?></div>
		<div class="mTop5">
			<? if(isset($fbprofile['location'])) { ?>
			<span><i class="infoBox livein"></i>Sống tại <a href="http://www.facebook.com/pages/<?=$fbprofile['location']['name']?>/<?=$fbprofile['location']['id']?>"><?=$fbprofile['location']['name']?></a> </span>
			<? } ?>
			<? if(isset($fbprofile['hometown'])) { ?>
			<span class="mLeft5"><i class="infoBox comefrom"></i>Đến từ <a href="http://www.facebook.com/pages/<?=$fbprofile['hometown']['name']?>/<?=$fbprofile['hometown']['id']?>"><?=$fbprofile['hometown']['name']?></a> </span>
			<? } ?>
			<div class="c"></div>
		</div>
	</div>
	<div class="mTop20 mBottom30 shareBox">
		<div id="previewBox" class="mBottom5 hidden"><a id="owner" href="<?=$fbme['link']?>" target="_blank" class="b" title="<?=$fbme['name']?>"><?=$fbme['name']?></a> tin rằng: <span id="previewOwner"></span> <span id="previewContent"></span></div>
		<div class="c"></div>
		<div class="mTop5">
			<div><input type="textbox" id="iptPost" name="iptPost" value="Bạn đang tin điều gì?" style="padding:5px;width:510px;border: 1px solid #CCC;color:#999"/></div>
			<div class="mTop5">
                <div class="fl" style="width:440px">
                    <label for="chkOwner">
                        <input type="checkbox" id="chkOwner" name="chkOwner" /> Điều này nói về
						<span id="idOwner"><? if($fbme['id'] == $fbprofile['id']) {?>bạn <? } else { ?><?=$fbprofile['name']?> <? } //if?></span>
                    </label>
                </div>
                <div class="fl" style="width:80px;text-align:right;">
					<label class="btnShare emButton emButtonConfirm emButtonLarge" for="btnShare">
						<input type="button" id="btnShare" value="Chia sẻ" />
					</label>
				</div>
                <div class="c"></div>
            </div>
		</div>
		<div class="c"></div>
	</div>

	<ul class="emStream">
	<?
	if(count($myBelive) > 0) {
	$i=0;
	foreach($profilePost as $k => $v) {
		$arrBeliveFBID = ($v['belivers'] != '')? unserialize($v['belivers']) : array();
		$fbposter = array (
			'id' => $v['fbid'],
			'name' => $v['fbname'],
			'link' => $v['fblink']
		);
		$i++;
	?>
	<li <? if($i == 1) { ?>class="first"<? } ?>>
		<div class="">
			<div class="fl w60"><?=FaceLib::getProfileImage($fbprofile)?></div>
			<div class="fl" style="max-width:460px">
				<div style="color:#808080"><span class="b"><?=FaceLib::getProfileName($fbprofile)?></span> <?=PostLib::getOtherBelive($v, $fbprofile['id'], $v['fbid'])?></div>
				<div class="mTop5 f12 postContent"><?=PostLib::getContentBelive($v)?></div>
				<div class="mTop5">
					<?=PostLib::getOtherBeliveImage($v, $fbprofile['id'], $v['fbid'], 10)?>
				</div>
				<div class="mTop10 postQuote">
					<?= FunctionLib::FacebookTimeFormat($v['created']) ?> ·
					<? if(!empty($arrBeliveFBID[$fbme['id']])) { ?>
					<a href="javascript:void(0)" onclick="emmua.postBox.unbelive(this, <?=$v['id']?>);">Bỏ tin điều này</a> ·
					<? } else { ?>
					<a href="javascript:void(0)" onclick="emmua.postBox.belive(this, <?=$v['id']?>);">Tin điều này</a> ·
					<? } ?>
					<a href="javascript:void(0)" onclick="emmua.postBox.shareBeliveToWall(<?=$fbprofile['id']?>, <?=$v['id']?>)">Chia sẻ niềm tin này</a>
				</div>
			</div>
			<div class="c"></div>
		</div>
	</li>
	<? } //foreach
	} else { ?>
	<li <? if($i == 0) { ?>class="first"<? } ?>>
		<div class="p10" style="border:1px dashed #B3B3B3">
			<div class="fl w60"><?=FaceLib::getProfileImage($fbme)?></div>
			<div class="fl" style="max-width:460px">
				Hãy tin điều gì đó về cuộc sống hoặc về bạn, hoặc về bạn bè
			</div>
			<div class="c"></div>
		</div>
	</li>
	<? } //if?>
	</ul>
</div>
<div class="c"></div>
</form>

<? }//ìf user?>
</body>
</html>